<template>
  <div>
    <!-- 抽屉组件 -->
    <a-modal
      width="780px"
      :title="$t('all.autotext1324')"
      :visible="uploadFileVisible"
      :footer="null"
      @cancel="closeUpload"
      dialogClass="upload-modal"
    >
      <slot name="title" >
        <div class="upload-btn-wrapper">
          <div>
            <a-upload
              ref="import"
              name="file"
              accept=".pdf, .jpg, .jpeg, .png"
              :multiple="true"
              :before-upload="beforeUploadSite"
              :customRequest="handleUpload"
              :showUploadList="false"
            >
              <!-- <a-button style="margin-bottom: 10px" :loading="currentTarget.loading" :disabled="currentTarget.btnSwitch"><a-icon type="upload" v-if="!currentTarget.loading" />上传</a-button> -->
              <a-button type="primary" class="upload-btn btn1" :loading="uploading">
                {{ dataInfo.fileList && dataInfo.fileList.length ? $t('all.autotext278') : $t('all.autotext101') }}
              </a-button>
            </a-upload>
            <a-popconfirm :title="$t('all.autotext14') + '？'" @confirm="clearAll">
              <a-button class="upload-btn btn2" style="margin-left: 24px">{{ $t('all.autotext1473') }}</a-button>
            </a-popconfirm>
          </div>
          <a-checkbox class="checkbox--right" v-model="autoDesensitizationCheck" :disabled="uploading">{{ $t('all.autotext614') }}</a-checkbox>
        </div>
      </slot>
      <a-table :data-source="dataInfo.fileList" :rowKey="record => record.uniqueId" :pagination="false">
        <a-table-column :title="$t('all.autotext334')" data-index="order">
          <template slot-scope="text,record,index">{{ index + 1 }}</template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext215')" data-index="originalFile">
          <template slot-scope="text,record"><a @click="preview(record.fileUrl)">{{ record.fileName }}</a></template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext582')" data-index="afterFile">
          <template slot-scope="text,record, index">
            <div class="afterfile">
              <template v-if="desensePassed(record)">
                <a class="filename" @click="preview(record.afterFileUrl)">{{ record.fileName }}</a>
                <a @click="editFile(record, index)">{{ $t('all.autotext1231') }}</a>
              </template>
              <template v-else>
                <span class="grey" v-if="record.afterFileUrl">{{ $t('all.autotext881') }}</span>
                <a @click="editFile(record, index, 2)">{{ $t('all.autotext236') }}</a>
              </template>
            </div>
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext187')" data-index="operate">
          <template slot-scope="text,record">
            <a @click="clickViewFile(record)">{{ $t('all.autotext84') }}</a>
            <a-divider type="vertical" />
            <a-popconfirm :title="$t('all.autotext688')" @confirm="deleteFile(record)">
              <a class="table-operator__btn--danger">{{ $t('all.autotext379') }}</a>
            </a-popconfirm>
          </template>
        </a-table-column>
      </a-table>
    </a-modal>
    <!-- 图片预览 -->
    <a-modal
      width="50%"
      :visible="imgVisible"
      :footer="null"
      @cancel="imgVisible = false"
    >
      <div class="image">
        <img key="itemFileUrl" :src="itemFileUrl | dealImageUrl">
      </div>
    </a-modal>
    <DesensitizationModal
      ref="desensitization"
      v-bind="{...desensDialog}"
      @ok="handleDesensDialogOk"
      @cancel="handleDesensDialogCancel"
    />
  </div>
</template>

<script>
import { uploadFile, apiUploadPdf2Img } from '@/api/common'
import { apiMosaicUploadNew } from '@api/cost/cost'
import DesensitizationModal from '../../../../cost-apply/components/desensitizationModal.vue'

export default {
  components: { DesensitizationModal },
  props: {
    currentTarget: {
      type: Object,
      default: () => {
        return {}
      }
    },
    uploadFileVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      dataInfo: {},
      imgVisible: false,
      itemFileUrl: '',
      uploading: false,
      autoDesensitizationCheck: true,
      desensDialog: {
        type: 'edit',
        visible: false,
        originalFileUrl: '',
        afterFileUrl: '',
        selectRowIndex: 0,
        fileName: 'name'
      }
    }
  },
  methods: {
    // 赋值
    copyData (data) {
      this.dataInfo = data
    },
    // 切换条目再打开弹窗时重置部分初始值
    resetData () {
      this.autoDesensitizationCheck = true
    },
    beforeUploadSite (file) {
      const formatImg = /((gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      const formatPdf = /(pdf)$/i
      // const formatWord = /((doc|docx|wps))$/i
      const formatWord = /((msword|vnd.openxmlformats-officedocument.wordprocessingml.document|kswps))$/i
      if (formatImg.test(file.type)) {
        return true
      } else if (formatPdf.test(file.type)) {
        return true
      } else if (formatWord.test(file.type)) {
        return true
      } else {
        this.$message.error(this.$t('all.autotext293'))
        return false
      }
    },
    // 修改上传
    handleUpload ({ file }) {
      // 校验格式
      const info = {}
      this.uploading = true
      // 将上传的文件进行展示
      info.fileName = file.name
      info.uniqueId = Math.random().toString().substr(2, 10)
      this.$forceUpdate()
      const isPdfFormat = /pdf$/i.test(file.type)
      const request = this.autoDesensitizationCheck
        ? apiMosaicUploadNew
        : isPdfFormat
          ? apiUploadPdf2Img
          : uploadFile
      const params = new FormData()
      params.append('file', file)
      return request(params, function (e) {
        if (e.lengthComputable) {
          let rate = e.loaded / e.total // 已上传的比例
          console.log('rate', rate)
        }
      }).then(res => {
        if (this.autoDesensitizationCheck) {
          info.fileUrl = res.originalUrl
          info.afterFileUrl = res.afterUrl
        } else {
          info.fileUrl = res
        }
        // 上传后保存文件服务器地址到本地
        if (this.dataInfo.fileList) {
          this.dataInfo.fileList.push(info)
        } else {
          this.dataInfo.fileList = []
          this.dataInfo.fileList.push(info)
        }
      }).catch(() => {
      }).finally(() => {
        this.uploading = false
      })
    },
    // 关闭弹窗
    closeUpload () {
      this.$emit('closeUpload', this.dataInfo)
    },
    /**
     * 设置脱敏弹窗的文件
     * @param fileUrl 原始文件 半路径
     * @param afterFileUrl 脱敏后文件 半路径
     */
    setDenseModalFile (fileUrl, afterFileUrl) {
      this.desensDialog.originalFileUrl = this.$options.filters.dealImageUrl(fileUrl)
      this.desensDialog.afterFileUrl = this.$options.filters.dealImageUrl(afterFileUrl)
    },
    // 对比预览
    clickViewFile ({ fileUrl, afterFileUrl }) {
      this.setDenseModalFile(fileUrl, afterFileUrl)
      this.desensDialog.visible = true
      this.desensDialog.type = 'preview'
    },
    // 单文件预览
    preview (fileUrl) {
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      if (formatImg.test(fileUrl)) {
        this.itemFileUrl = fileUrl
        this.imgVisible = true
      } else {
        // 打开空白页 展示文件
        const fullFileUrl = this.$options.filters.dealImageUrl(fileUrl)
        window.open(fullFileUrl, '_blank')
      }
    },
    // 点击删除上传的文件
    deleteFile (row) {
      const newList = this.dataInfo.fileList.filter(item => item.uniqueId !== row.uniqueId)
      this.dataInfo.fileList = newList
      this.$forceUpdate()
    },
    /**
     * 调整文件
     * @param afterFileUrl
     * @param fileName
     * @param fileUrl
     * @param index
     * @param type 调整还是手动脱敏 1-调整 2-手动脱敏
     */
    editFile ({ afterFileUrl, fileName, fileUrl }, index, type = 1) {
      this.desensDialog.type = 'edit'
      this.desensDialog.selectRowIndex = index
      this.setDenseModalFile(fileUrl, type === 2 ? fileUrl : afterFileUrl)
      this.desensDialog.fileName = fileName
      this.desensDialog.visible = true
      this.$nextTick(() => {
        this.$refs.desensitization.init()
      })
    },
    /**
     * @function 手动脱敏
     */
    desensitization () {
      this.desensDialog.visible = true
    },
    // 清空全部
    clearAll () {
      this.dataInfo.fileList = []
      this.$forceUpdate()
    },
    handleDesensDialogOk (fileUrl) {
      const selectRow = this.dataInfo.fileList[this.desensDialog.selectRowIndex]
      if (selectRow) {
        this.$set(selectRow, 'afterFileUrl', fileUrl)
      }
    },
    handleDesensDialogCancel () {
      this.desensDialog = {
        type: 'edit',
        visible: false,
        originalFileUrl: '',
        afterFileUrl: '',
        selectRowIndex: 0,
        fileName: 'name'
      }
    },
    // 脱敏通过
    desensePassed ({ fileUrl, afterFileUrl }) {
      return afterFileUrl && afterFileUrl !== fileUrl
    }
  }
}
</script>
<style scoped lang="less">
.ant-modal-body {
  .checkbox--right {
    float: right;
    line-height: 32px;
  }
  .ant-table-tbody {
    td {
      .afterfile {
        width: 200px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .table-operator__btn--danger {
        color: #F02F2F;
      }
      .grey {
        color: #999999;
      }
    }
  }
}
.image {
  img {
    display: block;
    width: 80%;
    margin: 10px auto;
  }
}
.file-icon {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-right: 10px;
}
div /deep/ .ant-modal-header{
  padding: 32px;
  border-bottom: none;
  &>div {
    color:#031F47;
    line-height: 30px;
    font-size: 20px;
    font-weight: 400;
  }
}
div /deep/ .ant-modal-body {
  padding-top: 0px;
}
.upload-btn-wrapper{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  .upload-btn {
    min-width: 88px;
    height: 32px;
    font-size: 14px;
    line-height: 22px;
    border-radius: 4px;
  }
  .btn1 {
    background: #0578B8;
    color: #fff;
  }
  .btn2 {
    border-color: #0578B8;
    color: #0578B8;
  }
}


</style>
